package com.luohoufa.ms.apigateway.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenGenerator {

    private static final String CLAIM_KEY_SUB = "sub";
    private static final String CLAIM_KEY_CREATED = "created";

    /**
     * jwt 加密解密密钥
     */
//    @Value("${jwt.secret}")
    private String jwtSecret;

    /**
     * 根据userId生成Token
     * @param userId
     * @return
     */
    public String generateToken(String userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_SUB, userId);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * 刷新Token
     * @param token
     * @return
     */
    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * 从Token中获取userId
     * @param token
     * @return
     */
    public String getUserIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        Object object = claims.get(CLAIM_KEY_SUB);
        return object==null ? null : String.valueOf(object);
    }

    /**
     * 验证Token是否有效
     * @param token
     * @return
     */
    public Boolean verifyToken(String token) {
        String userId = getUserIdFromToken(token);
        if (StringUtils.isEmpty(userId)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 从Token中获取创建时间
     * @param token
     * @return
     */
    private Date getCreatedDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        Object object = claims.get(CLAIM_KEY_CREATED);
        return object==null ? null : new Date((Long) object);
    }

    /**
     * 从Token中获取过期时间
     * @param token
     * @return
     */
    private Date getExpirationDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }



    /**
     * 从Token中获取Claims信息
     * @param token
     * @return
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(jwtSecret)
                .parseClaimsJws(token).getBody();
        return claims;
    }

    /**
     * 根据Map生成Token
     * @param claims
     * @return
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }

}
